<?php

namespace zhtfrontend\models\datas;

use common\components\helpers\Fun;
use Yii;
use yii\helpers\ArrayHelper;
use common\components\behaviors\UpdateCacheBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use common\components\extenders\MenuManage;
use doumiaoduo\ueditor\ImageUploadMultipleTrait2;

/**
 * This is the model class for table "{{%mechanic}}".
 *
 * @property integer $id
 * @property string $number
 * @property string $name
 * @property string $picture
 * @property integer $site_id
 * @property string $info
 * @property string $description
 * @property integer $user_id
 * @property integer $created_at
 * @property integer $enrollment
 * @property integer $admin_id
 */
class Mechanic extends \zhtfrontend\components\bases\BaseModel
{
    use ImageUploadMultipleTrait2;
    public $high;
    public $middle;
    public $low;
    public $mechanic_username;//机构管理员
    public $mec_principal;//将机构校长部分的功能从管理员部分移动到机构部分，这个机构的角色我是真的懵逼了不敢碰，只能保持的基础上加了
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%mechanic}}';
    }

    /**
     * @return \yii\db\Connection the   `database connection used by this AR class.
     */

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['site_id', 'user_id', 'created_at', 'status','reduction'], 'integer'],
            [['name','admin_id'], 'required'],
            [['enrollment_ratio','return_ratio'], 'number'],
            [['info', 'description','picture','proportion','regist_name','mechanic_username'], 'string'],
            [['name','regist_name'], 'string', 'max' => 60],
            ['contacts', 'string','max' => 10],
            ['telephone', 'string','max' => 11],
            [['enrollment', 'number'], 'safe'],
            [['mec_principal'], 'required'],
            [['mechanic_username'], 'required','on'=>['create']],
            [['mechanic_username'], 'mechanic_unique','on'=>['create']],
            [['enrollment'], 'required','on'=>['create','update']],
            [['enrollment'], 'integer','on'=>['create','update']],
            [['enrollment'], 'check_number','on'=>['create','update']],
            [['contacts','telephone','regist_name'],'required','except'=>['update_show']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('zhtfrontend', '序号'),
            'number' => Yii::t('zhtfrontend', '编号'),
            'regist_name' => Yii::t('zhtfrontend', '公司注册名称'),
            'name' => Yii::t('zhtfrontend', '别名'),
            'picture' => Yii::t('zhtfrontend', 'LOGO'),
            'site_id' => Yii::t('zhtfrontend', '分店编号'),
            'info' => Yii::t('zhtfrontend', '简介'),
            'description' => Yii::t('zhtfrontend', '机构描述'),
            'user_id' => Yii::t('zhtfrontend', '添加人'),
            'created_at' => Yii::t('zhtfrontend', '创建时间'),
            'status' => Yii::t('zhtfrontend', '合作状态'),
            'parent_id'=>Yii::t('zhtfrontend', '所属机构'),
            'is_delete'=>Yii::t('zhtfrontend', '是否删除'),
            'region'=>Yii::t('zhtfrontend', '所在地区'),
            'enrollment'=>Yii::t('zhtfrontend', '招生人数'),
            'proportion'=>Yii::t('zhtfrontend', '招生比例'),
            'high'=>Yii::t('zhtfrontend', '招生比例 高'),
            'middle'=>Yii::t('zhtfrontend', '招生比例 中'),
            'low'=>Yii::t('zhtfrontend', '招生比例 低'),
            'imageList'=>Yii::t('zhtfrontend', '图片'),
            'altList'=>Yii::t('zhtfrontend', '图片描述'),
            'contacts'=>Yii::t('zhtfrontend', '联系人'),
            'telephone'=>Yii::t('zhtfrontend', '联系电话'),
            'coordinates'=>Yii::t('zhtfrontend', '地理坐标'),
            'address'=>Yii::t('zhtfrontend', '详细地址'),
            'admin_id'=>Yii::t('zhtfrontend', '负责人'),
            'reduction' => Yii::t('zhtfrontend', '减免课时费的课次数'),
            'return_ratio' => Yii::t('zhtfrontend', '课时费返现比例'),
            'enrollment_ratio' => Yii::t('zhtfrontend', '招生比例'),
            'mechanic_username' => Yii::t('zhtfrontend', '普通管理员账号'),
            'mec_principal' => Yii::t('zhtfrontend', '机构校长'),
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['status'] = function () {
            switch ($this->status) {
                case 0:
                    return \Yii::t('zhtfrontend', '未开始');
                case 1:
                    return \Yii::t('zhtfrontend', '合作中');
                case 2:
                    return \Yii::t('zhtfrontend', '已结束');
            }
        };

        $fields['mec_principal'] = function (){
            //$this->id;
            $admin = Admin::findOne(['role'=>'mec_principal',['mechanic_id' => $this->id]]);
            if(!empty($admin)){
                return $admin->id;
            }else{
                return null;
            }
            //$admin_arr = Admin::findAll(['role'=>'mec_principal',['or', ['mechanic_id' => null], ['mechanic_id' => [0,$this->mechanic_id]]]]);//列出所有可以进行选择的机构校长管理员

        };

        return $fields;
    }

    public function extraFields()
    {
        return [
            'zhtfrontend_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'delete' => function ($data) {
                            $teacher = Teacher::find()->select('mechanic_id')->where("mechanic_id!=''")->distinct('mechanic_id')->column();
                            $course = Course::find()->select('mechince_id')->where("mechince_id!=''")->distinct('mechince_id')->column();
                            $mechanic = array_merge($teacher,$course);
                            $mechanic = array_unique($mechanic);
                            if ($mechanic != null && in_array($data['id'], $mechanic)) {
                                return '<button class="yx-btn-disabled" disabled>删除</button>';
                            } else {
                                return '';
                            }
                        },
                        'update' => function ($data) {
                            return '';
                        },
                        'create'=>function($data){

                                return '<button style="border: none;background-color:#fff;" disabled></button>';

                        },
                        'recovery' => function($data){
                        if($data['is_delete'] == 0) {
                            return '<button class="yx-btn-disabled" disabled>恢复</button>';
                        }else{
                            return '';
                        }
                },
                    ]
                )->create();
            },

        ];


    }
    public function check_number($attribute){
        $parent_id = $this->parent_id;
        if ($parent_id != 0 && $parent_id != null) {
            $enrollment_all = Mechanic::find()->select('enrollment')->where(['id' => $parent_id])->asArray()->one();
            $enrollment_add = Mechanic::find()->select('enrollment')->where(['parent_id' => $parent_id])->andWhere(['<>','id',$this->id])->sum('enrollment');
            $add_now = (int)$enrollment_add + (int)$this->$attribute;
            if ((int)$enrollment_all['enrollment'] < $add_now) {
                $this->addError($attribute, \Yii::t('zhtfrontend', '分店的招生人数之和不可以大于总店的招生人数！！'));
            }
        }
    }


    public function check_proportion($attribute){
        $high=!empty($this->high)?$this->high:0;
        $middle=!empty($this->middle)?$this->middle:0;
        $low=!empty($this->low)?$this->low:0;
        $sum=$high+$middle+$low;
        if(!empty($this->parent_id)){
            if($this->high==null || $this->middle==null || $this->low==null){
                $this->addError($attribute, \Yii::t('zhtfrontend', '必填项！'));
            }
        }
        if($sum>100){
            $this->addError($attribute, \Yii::t('zhtfrontend', '总比例之和为{sum},不能超过100！',['sum'=>$sum]));
        }
        if($this->high!=null && $this->middle!=null && $this->low!=null){
            $total=$this->high+$this->middle+$this->low;
            if($total!=100){
                $this->addError($attribute, \Yii::t('zhtfrontend', '总比例之和为{total},不等于100！',['total'=>$total]));
            }
        }
    }

    public function mechanic_unique($attribute){
         $model = Admin::find()->where(['username'=>$this->$attribute])->one();
         if($model != null){
             $this->addError($attribute, \Yii::t('zhtfrontend', '此管理员账号已存在！'));
         }
    }
    public function afterSave($insert, $changedAttributes){
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            $model = new Admin();
            $model->username = $this->mechanic_username;
            $model->email = $this->mechanic_username.'@126.com';
            $model->mechanic_id = $this->id;
            $model->name = $this->name;
            $model->role = 'mechanic';
            $model->created_at = $this->created_at;
            $model->password = \Yii::$app->security->generatePasswordHash($this->telephone);
            if ($model->save(false)) {
                $auth = \Yii::$app->authManager;
                $auth->assign($auth->getRole($model->role), $model->id);
            }
        }else{
            if($this->status == 2){
                Course::updateAll(['status'=>2],['mechince_id'=>$this->id]);
                Teacher::updateAll(['status'=>0],['mechanic_id'=>$this->id]);
                Headmaster::updateAll(['status'=>0],['mechanic_id'=>$this->id]);
                Goods::updateAll(['is_delete'=>1,'is_shelve'=>0],['mechanic_id'=>$this->id]);
                Arrangement::updateAll(['is_delete'=>1],['mechanic_id'=>$this->id]);
                Admin::updateAll(['status'=>0],['mechanic_id'=>$this->id,'role'=>'mechanic']);
                $teacher_ids = Teacher::find()->select('id')->where(['mechanic_id'=>$this->id])->column();
                Admin::updateAll(['status'=>0],['teacher_id'=>$teacher_ids,'role'=>'teache_teacher']);
               $headIds = Headmaster::find()->select('id')->where(['mechanic_id'=>$this->id])->column();
                Admin::updateAll(['status'=>0],['teacher_id'=>$headIds,'role'=>'class_teacher']);
                ClassManage::updateAll(['is_delete'=>1],['mechanic_id'=>$this->id]);
            }elseif ($this->status == 1){
                Course::updateAll(['status'=>1],['mechince_id'=>$this->id]);
                Teacher::updateAll(['status'=>1],['mechanic_id'=>$this->id]);
                Headmaster::updateAll(['status'=>1],['mechanic_id'=>$this->id]);
                Goods::updateAll(['is_delete'=>0],['mechanic_id'=>$this->id]);
                Arrangement::updateAll(['is_delete'=>0],['mechanic_id'=>$this->id]);
                Admin::updateAll(['status'=>1],['mechanic_id'=>$this->id,'role'=>'mechanic']);
                $teacher_ids = Teacher::find()->select('id')->where(['mechanic_id'=>$this->id])->column();
                Admin::updateAll(['status'=>1],['teacher_id'=>$teacher_ids,'role'=>'teache_teacher']);
                $headIds = Headmaster::find()->select('id')->where(['mechanic_id'=>$this->id])->column();
                Admin::updateAll(['status'=>1],['teacher_id'=>$headIds,'role'=>'class_teacher']);
                ClassManage::updateAll(['is_delete'=>0],['mechanic_id'=>$this->id]);
            }
        }
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => UpdateCacheBehavior::className(),
                'cacheName' => 'mechanic',

            ],
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ],
            ],
        ]);
    }
}
